from captcha.models import CaptchaStore
from django_redis import get_redis_connection
from captcha.conf import settings as ca_settings
from captcha.helpers import captcha_image_url, captcha_audio_url
from rest_framework.views import APIView
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, ListModelMixin, DestroyModelMixin
from rest_framework.generics import GenericAPIView
from admin.utils.filter import MyUserFilter
from .models import UserInfo, OnlinUser
from .serializer import UserSerializer, UserInfoSerializer, GetUserSerializer
from rest_framework.response import Response
from admin.utils.auth import MyAuth
from admin.utils.page import Mypage
from rest_framework.filters import SearchFilter
from utils.excel import Xlwt_Export


class CaptchaView(APIView):
    authentication_classes = []
    permission_classes = []
    def get(self, request):
        conn = get_redis_connection('code')
        new_key = CaptchaStore.pick()
        to_json_response =  {
            'uuid': 'code-key-'+new_key,
            "img": captcha_image_url(new_key),
            "audio_url": captcha_audio_url(new_key) if ca_settings.CAPTCHA_FLITE_PATH else None,
        }
        code = CaptchaStore.objects.filter(hashkey=new_key).values('response').first().get('response')
        conn.set('code-key-%s'%new_key, code)
        conn.expire('code-key-%s'%new_key, 300)
        return Response(data=to_json_response)


class UserView(GenericViewSet, CreateModelMixin):
    authentication_classes = []
    queryset = UserInfo.objects.filter(is_delete=False, enabled=True)
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data, context={'request': request})
        if ser.is_valid():
            token = ser.context.get('token')
            users = ser.context.get('user')               # 要登录用户对象
            data = {}
            user = {}
            user['dataScopes'] = []
            roles_list = []
            for i in users.roles.all():
                roles_list.append({
                    i.name
                })
            user['user'] = {
                'avatarPath': 'http://127.0.0.1:8000/media/'+ str(users.avatar_path),
                'createTime': users.create_time,
                'dept': {
                    'id': users.dept.pk,
                    'name': users.dept.name
                },
                'email': users.email,
                'enabled': users.enabled,
                'gender': users.gender,
                'id': users.pk,
                'jobs': [ {'id': i.pk, 'name': i.name}  for i in users.job.all()],
                'nickName': users.nick_name,
                'phone': users.phone,
                'pwdResetTime': users.pwd_reset_time,
                'roles': [ {'dataScope': i.data_scope, 'id': i.pk, 'level': i.level, 'name': i.name} for i in users.roles.all()],
                'updateBy': users.update_by,
                'updateTime': users.update_time,
                'username': users.username,
            }
            user['roles'] = roles_list
            data['token'] = 'Bearer '+ token
            data['user'] = user
            return Response(data=data)
        else:
            return Response('no')


class UserInfoView(GenericViewSet, ListModelMixin):
    authentication_classes = [MyAuth, ]
    queryset = UserInfo.objects.filter(is_delete=False)
    serializer_class = UserInfoSerializer
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset(request))
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data[0])
    def get_queryset(self, request):
        return UserInfo.objects.filter(username = request.user.username)




class GetUserView(GenericViewSet, ListModelMixin):
    queryset = UserInfo.objects.filter(is_delete=False).order_by('id')
    serializer_class = GetUserSerializer
    filter_backends = [SearchFilter, MyUserFilter]
    search_fields = ['username', 'email', 'nick_name', 'create_time', 'enabled']
    pagination_class = Mypage


class LogoutView(GenericAPIView):
    def delete(self, request):
        UserInfo.objects.filter(pk=request.user.pk).update(is_login=False)
        OnlinUser.objects.filter(user_id=request.user.pk).update(is_delete=True, update_by=request.user.username)
        return Response()

class DownloadUserView(APIView):
    def get(self, request):
        data = UserInfo.objects.values()
        Xlwt_Export(data, 'sheet1', '')
        # Xlwt_Export('sys_user')
        return Response('ok')